package main

import (
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/sirupsen/logrus"

	"github.com/dreamSailing/http-proxy/internal/mcp"
	"github.com/dreamSailing/http-proxy/internal/proxy"
)

func main() {
	// 初始化日志（仅控制台输出）
	logger := logrus.New()
	logger.SetLevel(logrus.InfoLevel)
	logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: time.RFC3339,
	})
	logger.SetOutput(os.Stdout)

	logger.Info("Logger initialized with console output")

	// 创建上下文
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 初始化HTTP代理引擎
	proxyEngine := proxy.NewEngine(logger)

	// 初始化MCP服务器
	mcpServer, err := mcp.NewServer(logger, proxyEngine)
	if err != nil {
		logger.Fatalf("Failed to create MCP server: %v", err)
	}

	// 设置信号处理
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// 启动MCP服务器
	go func() {
		logger.Info("Starting MCP server...")
		if err := mcpServer.Start(ctx); err != nil {
			logger.Errorf("MCP server failed: %v", err)
			cancel()
		}
	}()

	logger.Info("MCP HTTP Proxy Server started and listening on stdio")

	// 等待中断信号
	<-sigChan

	logger.Info("Shutting down MCP server...")

	// 优雅关闭
	if err := mcpServer.Shutdown(ctx); err != nil {
		logger.Errorf("Failed to shut down MCP server gracefully: %v", err)
	}

	logger.Info("MCP server shut down gracefully")
}
